// routes/api.js
const express = require('express');
const testDataGenerator = require('../services/Code2TestData');
const clientGenerator = require('../services/HttpRequest2ClientCode');
const docGenerator = require('../services/HttpRequest2Docs');


const router = express.Router();

/**
 * 生成请求数据
 * POST /api/generate-tests-from-code
 * Body: { code: string}
 */
router.post('/generate-tests-from-code', async (req, res) => {
    try {
        const { code } = req.body;
        if (!code) return res.status(400).json({ error: '代码不能为空' });
        const testCases = await testDataGenerator.generateTestDataFromCode(
            code
        );
        res.json(testCases);
    } catch (error) {
        handleError(res, error);
    }
});

/**
 * 生成客户端代码
 * POST /api/generate-client
 * Body: { requestDesc: string, techStack?: string }
 */
router.post('/generate-client', async (req, res) => {
    try {
        const { requestDesc, techStack = 'axios' } = req.body;

        if (!requestDesc) {
            throw new Error('HTTP请求描述不能为空');
        }

        const clientCode = await clientGenerator.generateRequestCode(requestDesc, techStack);
        res.json({
            success: true,
            data: {
                techStack,
                clientCode
            }
        });
    } catch (error) {
        handleError(res, error);
    }
});

/**
 * 生成API文档
 * POST /api/generate-docs
 * Body: { requestDesc: string, format?: string }
 */
router.post('/generate-docs', async (req, res) => {
    try {
        const { requestDesc, format = 'markdown' } = req.body;

        if (!requestDesc) {
            throw new Error('HTTP请求不能为空');
        }

        const documentation = await docGenerator.generateDocumentation(requestDesc, format);
        res.json({
            success: true,
            data: {
                format,
                content: documentation
            }
        });
    } catch (error) {
        handleError(res, error);
    }
});


// 统一错误处理
function handleError(res, error) {
    console.error('API错误:', error);
    const status = error.message.includes('无效') ? 400 : 500;
    res.status(status).json({
        error: error.message,
        details: process.env.NODE_ENV === 'development' ? error.stack : undefined
    });
}

module.exports = router;


